package cn.fancy.sdk.login.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.common.utils.LoginSwitchManage;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.config.GlobalConfig;
import cn.fancy.sdk.entity.DevBase;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.DeleteUserDialog;
import cn.fancy.sdk.login.DeleteUserDialog.DeleteCallback;
import cn.fancy.sdk.login.QdLoginResult;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.pay.WebViewActivity;
import cn.fancy.sdk.utils.CheckLoginStateUtil;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.DensityUtil;
import cn.fancy.sdk.utils.SpMmkvUtils;
import cn.fancy.sdk.utils.TipMessSingle;
import com.bytedance.applog.game.GameReportHelper;
import java.util.ArrayList;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public class LoginView extends BaseView implements OnItemClickListener {
    
    private IActivityManager activityMgr;
    private static EditText usernameEt, passwordEt;
    private PopupWindow popupWindow = null;
    private ListView popListView = null;
    private AccountShowAdatper adapter = null;
    public ArrayList<LoginView.Account> acctArray = new ArrayList<>();
    static public String staticusername, staticpassword, savepoint,
        staticdeleteusername;
    private SdkAsyncTask<String> loginSyncTask, onekeySyncTask;
    private LayoutInflater inflater;
    private DBHelper dbHelper;
    private DeleteUserDialog deleteDialog;
    private ArrayList<DBHelper.SDK_ACCOUNT> db_valid_accts = new ArrayList<DBHelper.SDK_ACCOUNT>();
    private ArrayList<AccountHelper.Local_Account> local_valid_accts = new ArrayList<AccountHelper.Local_Account>();
    public static boolean auto_cancel = false;
    private Activity ownerActivity;
    private Context mContext;
    private ImageView guild_login_down_img;
    private ImageView guide_passseen;
    private LinearLayout acctDownIV;
    public static Boolean chooseCurrentUser = false;
    private static int currentpostion = 0;
    
    private RelativeLayout rl_whole;
    private LinearLayout ll_agreement;
    private CheckBox cb_agreement;
    private TextView link_agreement;
    private TextView tv_agreement;
    private View view_bottom_line;
    private TextView one_key_register, tv_realiden, tv_user_policy;
    private boolean needCheckBox;
    
    public LoginView(Context context) {
        super(context);
    }
    
    public LoginView(Activity cActivity, IActivityManager activityMgr) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(
            cActivity.getBaseContext(), "guild_login"));
        mContext = cActivity.getBaseContext();
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        
        inflater = LayoutInflater.from(this.getContext());
        dbHelper = DBHelper.getInstance(this.getContext());
        mContext = cActivity;
        savepoint = "0";
        
        initView();
        try {
            initAccount();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断是否是重置密码后跳转的
        judgeIfResetPassword();
    }
    
    @Override
    protected void onAttachedToWindow() {
        Log.e("isacccurr", "isacccurr" + usernameEt.getText().toString());
        
        updateAccount();
        activityMgr.showTitleBar(false);
        activityMgr.showLogoBar(View.GONE);
        
        // 重置一下当前user/pass
        CommMessage.sifLoginViewNow = true;
        
        if (DevBase.DevEnv.LOGO == 0) {
            if (DevBase.DevEnv.LOGO_BAR == 1) {
                activityMgr.showLogoBar(View.VISIBLE);
                activityMgr.showTitleBar(true);
            } else if (DevBase.DevEnv.LOGO_BAR == 0) {
                activityMgr.showLogoBar(View.GONE);
                /* 开启标题栏 */
                activityMgr.showTitleBar(false);
            }
        }
        this.postInvalidate();
        super.onAttachedToWindow();
    }
    
    @Override
    protected void onDetachedFromWindow() {
        activityMgr.showTitleBar(false);
        activityMgr.showLogoBar(View.VISIBLE);
        super.onDetachedFromWindow();
        CommMessage.sifLoginViewNow = false;
    }
    
    private void initView() {
        usernameEt = (EditText) this.findViewById(ResUtil.getId(mContext,
            "guild_login_username_et"));
        usernameEt.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        usernameEt.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        usernameEt.setNextFocusForwardId(ResUtil.getId(mContext,
            "guild_login_password_et"));
        usernameEt.setNextFocusDownId(ResUtil.getId(mContext,
            "guild_login_password_et"));
        
        passwordEt = (EditText) this.findViewById(ResUtil.getId(mContext,
            "guild_login_password_et"));
        passwordEt.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        
        TextView eyeImg = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_pass_down"));
        eyeImg.setSelected(false);
        passwordEt.setInputType(InputType.TYPE_CLASS_TEXT
            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        eyeImg.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                activityMgr.pushViewToStack(new FindPassMain(ownerActivity, activityMgr));
            }
        });
    
        one_key_register = (TextView) this.findViewById(ResUtil.getId(mContext,
            "one_key_register"));
        one_key_register.setOnClickListener(this);
        acctDownIV = (LinearLayout) this.findViewById(ResUtil.getId(mContext,
            "guild_login_down"));
        acctDownIV.setOnClickListener(this);
        TextView loginSubmitBt = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_login_submit_bt"));
        loginSubmitBt.setOnClickListener(this);
        
        guild_login_down_img = (ImageView) this.findViewById(ResUtil.getId(
            mContext, "guild_login_down_img"));
        ImageView guild_customserver = (ImageView) this.findViewById(ResUtil.getId(
            mContext, "guild_customserver"));
        guild_customserver.setOnClickListener(this);
        TextView guild_oneregister = (TextView) this.findViewById(ResUtil.getId(
            mContext, "tv_register"));
        guild_oneregister.setOnClickListener(this);
        
        guide_passseen = (ImageView) this.findViewById(ResUtil.getId(mContext,
            "guide_passseen"));
        guide_passseen.setOnClickListener(this);
    
        tv_realiden = (TextView) findViewById(ResUtil.getId(mContext, "tv_realiden"));
        tv_realiden.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                activityMgr.pushViewToStack(new RealMainCompleteView(ownerActivity, activityMgr));
            }
        });
    
        rl_whole = (RelativeLayout) this.findViewById(ResUtil.getId(mContext, "rl_whole"));
        ll_agreement = (LinearLayout) this.findViewById(ResUtil.getId(mContext, "ll_agreement"));
        cb_agreement = (CheckBox) this.findViewById(ResUtil.getId(mContext, "cb_agreement"));
        link_agreement = (TextView) this.findViewById(ResUtil.getId(mContext, "link_agreement"));
        tv_agreement = (TextView) this.findViewById(ResUtil.getId(mContext, "tv_agreement"));
        view_bottom_line = (View) this.findViewById(ResUtil.getId(mContext, "view_bottom_line"));
        tv_user_policy = (TextView) this.findViewById(ResUtil.getId(mContext, "tv_user_policy"));
        needCheckBox = needCheckBoxAgreeMent();
    }
    
    //===================是否展示同意协议
    private static final String DAIMIAO = "daimiao";
    private static final String AGREEMENT_URL = "/mobile/float/game_agreement";
    
    private boolean needCheckBoxAgreeMent() {
        if (GuildBaseInfo.getInstance().getMetaUrl("API_URL").contains(DAIMIAO)){
            link_agreement.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    //跳h5
                    String url = GuildBaseInfo.getInstance().getMetaUrl("API_URL") + AGREEMENT_URL;
                    WebViewActivity.start(getContext(), url, "游戏服务协议");
                }
            });
    
            one_key_register.setVisibility(GONE);
            tv_realiden.setVisibility(GONE);
            view_bottom_line.setVisibility(GONE);
    
            SpannableString ss = new SpannableString("请您阅读[用户协议]和[隐私政策]");
            
            ss.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 10,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    String url = "https://game.daimiaohudong.cn/mobile/float/game_agreement";
                    WebViewActivity.start(getContext(), url, "用户协议");
                }
            }, 4, 10,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
            ss.setSpan(new ForegroundColorSpan(Color.BLUE), 11, 17,  Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ss.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    String url = "https://game.daimiaohudong.cn/mobile/float/game_privacy";
                    WebViewActivity.start(getContext(), url, "隐私政策");
                }
            }, 11, 17,  Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            
            tv_user_policy.setMovementMethod(LinkMovementMethod.getInstance());
            tv_user_policy.setText(ss);
    
            ViewGroup.LayoutParams layoutParams = rl_whole.getLayoutParams();
            layoutParams.height = DensityUtil.dip2px(getContext(), 310);
            rl_whole.setLayoutParams(layoutParams);
            
            return true;
        } else {
            //隐藏协议，修改whole高度
            ViewGroup.LayoutParams layoutParams = rl_whole.getLayoutParams();
            layoutParams.height = DensityUtil.dip2px(getContext(), 300);
            rl_whole.setLayoutParams(layoutParams);
            ll_agreement.setVisibility(GONE);
            return false;
        }
    }
    
    private boolean verifyCheckBox(){
        if(needCheckBox && !cb_agreement.isChecked()){
            Toast.makeText(getContext(), "请先确认已阅读《游戏服务协议》", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    //===================是否展示同意协议end
    
    private void updateAccount() {
        db_valid_accts = dbHelper.getAllValidAccounts();
        
        if (db_valid_accts.size() > 0) {
            DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
            usernameEt.setText(acc.user_name);
            passwordEt.setText(acc.user_password);
        } else {
            local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext,true);
            
            if (local_valid_accts.size() > 0) {
                Local_Account temp = local_valid_accts.get(local_valid_accts
                    .size() - 1);
                usernameEt.setText(temp.username);
                passwordEt.setText(temp.password);
                Log.e("isacccurr4", "isacccurr4"
                    + usernameEt.getText().toString());
            }
        }
        if (!(CommMessage.currentUserName.equals(""))) {
            usernameEt.setText(CommMessage.currentUserName);
            passwordEt.setText(CommMessage.currentPassword);
            Log.e("isacccurr5", "isacccurr5" + usernameEt.getText().toString());
        }
    }
    
    private void initAccount() {
        // 先在本地sqlite 数据库中检测是否有用户名存在
        db_valid_accts = dbHelper.getAllValidAccounts();
        if (db_valid_accts.size() > 0) {
            DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
            usernameEt.setText(acc.user_name);
            passwordEt.setText(acc.user_password);
            
            if (!("".equals(acc.user_name.trim()))
                && !(CommMessage.isChangingAccount)
                && !("".equals(acc.user_password.trim()))) {
                if (CommMessage.getcanAutoLogin()) {
                    LoginView.this.startLogin();
                }
            }
        } else {
            local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext, true);
            if (local_valid_accts.size() > 0) {
                Local_Account temp = local_valid_accts.get(local_valid_accts
                    .size() - 1);
                usernameEt.setText(temp.username);
                passwordEt.setText(temp.password);
            } else {
                AccountHelper.Local_Account account = AccountHelper
                    .getLastestLoginAccountFromOldSdk(mContext);
                if (account.username != null && !"".equals(account.username)
                    && account.password != null
                    && !"".equals(account.password)) {
                    account.last_login_time = System.currentTimeMillis();
                    account.isValid = AccountHelper.ACCOUNT_VALID;
                    AccountHelper.updateLocalAccounts(account);
                    usernameEt.setText(account.username);
                    passwordEt.setText(account.password);
                } else {
                    usernameEt.setText("");
                    passwordEt.setText("");
                }
            }
        }
    }
    
    private void startLogin() {
        final String uname = usernameEt.getText().toString().trim();
        final String upass = passwordEt.getText().toString().trim();
        
        // 账号合法性检测
        if (uname.equals("")) {
            Toast.makeText(mContext, TipMessSingle.one_usernil,
                Toast.LENGTH_LONG).show();
            return;
        }
        if (upass.equals("")) {
            Toast.makeText(mContext, TipMessSingle.one_passnil,
                Toast.LENGTH_LONG).show();
            return;
        }
        // 当前没有网络连接
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        final Map<String, String> params = GuildBaseInfo.getInstance()
            .buildLoginGuild(getContext(), uname, upass);
        if (params == null) {
            Toast.makeText(getContext(), "传入参数有误...", Toast.LENGTH_LONG).show();
            return;
        }
        
        loginSyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                Log.e("loginparam", "loginparam" + params);
                return HttpReq.doGuildRequest(params);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                Log.e("loginnewrst", "loginnewrst" + rst);
                if (TextUtils.isEmpty(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String msg = json.getString("data");
                    JSONObject msgjson = new JSONObject(msg);
                    String bind_flag = "";
                    int need_bind = 0;
                    String cmCert;
                    if (TextUtils.isEmpty(msg)) {
                        return;
                    }
                    String token = msgjson.optString("ticket");
                    String time = String.valueOf(msgjson.getInt("expires_in"));
                    
                    String user_id = msgjson.optString("id");
                    if (msgjson.optString("status").equals("0")) {
                        Toast.makeText(getContext(), "帐号目前封禁", Toast.LENGTH_LONG).show();
                        return;
                    }
                    int float_window = msgjson.has("float_window") ? msgjson.optInt("float_window") : 0;
                    SpMmkvUtils.putValue(getOwnerActivity(),SpMmkvUtils.KEY_FLOAT_DISPLAY, String.valueOf(float_window));
    
                    if (TextUtils.isEmpty(msgjson.optString("float_window_url"))) {
                        String httpsFloatUrl = msgjson.getString("float_window_url");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_HTTPS_FLOAT_URL, httpsFloatUrl);
                    }
    
                    if (!TextUtils.isEmpty(msgjson.optString("game_discount"))) {
                        String discount = msgjson.getString("game_discount");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, discount);
                    }else {
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, "0");
                    }
                    
                    //need_bind = msgjson.optInt("openCellphone"); // 0不需绑定,1强制绑定,2可取消绑定
                    // isAdult防沉迷状态,0是,1否
                    cmCert = msgjson.optInt("isAdult") + "";
                    CommMessage.setCmCert(cmCert);
                    // 进行状态判断
                    LoginSwitchManage.getInstance().clearSwitch();
                    
                    // db数据库写一次,在包内；localaccount写一次，在包外
                    DBHelper.SDK_ACCOUNT s_acct = new DBHelper.SDK_ACCOUNT();
                    s_acct.auto_login = 1;
                    s_acct.user_name = uname;
                    s_acct.user_password = upass;
                    s_acct.is_valid = AccountHelper.ACCOUNT_VALID;
                    s_acct.user_id = user_id;
                    
                    Local_Account local_acct = new Local_Account();
                    local_acct.username = uname;
                    local_acct.password = upass;
                    local_acct.isValid = AccountHelper.ACCOUNT_VALID;
                    AccountHelper.updateLocalAccounts(local_acct);
                    
                    if (dbHelper.isAccountPresent(s_acct)) {
                        dbHelper.updateAccount(s_acct);
                    } else {
                        dbHelper.insertNewAccount(s_acct);
                    }
                    QdLoginResult loginResult = new QdLoginResult(user_id, uname, token, time, bind_flag, need_bind + "");
                    
                    CommMessage.currentUserName = usernameEt.getText().toString();
                    CommMessage.currentPassword = passwordEt.getText().toString();
                    GuildBaseInfo.getInstance().SetLoginAuMess(uname, upass, String.valueOf(LoginSwitchManage.getInstance().result_authenticate));
                    GuildBaseInfo.getInstance().setAccountInfo(uname, upass, user_id);
                    
                    GuildBaseInfo.setAcctsInfo(uname, user_id, upass);
                    CommMessage.setRealType("login");
                    Log.e("loginuser", "loginuser" + uname);
                    
                    GlobalConfig.ticket = token;
                    GlobalConfig.stime = time;
                    GlobalConfig.sUid = user_id;
                    
                    String bindState = msgjson.getString("pop_login_phone");
                    int testState = Integer.parseInt(bindState);
                    
                    int cardCheck = Integer.parseInt(msgjson.optString("pop_login_idcard"));
                    GlobalConfig.sRegCard = cardCheck;
                    int gameState = CheckLoginStateUtil.getState(testState, cardCheck);
                    
                    boolean bindMust = false;
                    if (testState == 1) {
                        bindMust = false;
                    } else if (testState == 2) {
                        bindMust = true;
                    }
                    
                    switch (gameState) {
                        case 0:
                            activityMgr.notifyLoginSuccess(loginResult);
                            activityMgr.finishDialogOrActivity();
                            break;
                        case 1:
                        case 2:
                            activityMgr.pushViewToStack(new RealViewMust(ownerActivity, activityMgr));
                            break;
                        default:
                            activityMgr.pushViewToStack(new BindPhoneMustView(
                                ownerActivity, activityMgr, bindMust, loginResult,
                                upass, user_id));
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
        };
        
        loginSyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    @Override
    public void stopSyncTask(boolean stop) {
        if (loginSyncTask != null) {
            loginSyncTask.cancel(stop);
        }
        if (onekeySyncTask != null) {
            onekeySyncTask.cancel(stop);
        }
    }
    
    private long ts = 0;
    
    @Override
    public void onClick(View v) {
        int vid = v.getId();
        
        long cts = System.currentTimeMillis();
        
        if (vid == ResUtil.getId(mContext, "guild_login_submit_bt")) {
            if(!verifyCheckBox()){
                return;
            }
            if ((cts - ts) > 2000) {
                ts = cts;
                startLogin();
            }
        } else if (vid == ResUtil.getId(mContext, "one_key_register")) {
            if(!verifyCheckBox()){
                return;
            }
            // 一键注册
            onekeyregister();
        } else if (vid == ResUtil.getId(mContext, "guild_login_down")) {
            popupWindowInit();
            if (popupWindow.isShowing() || 0 == acctArray.size()) {
                popupWindow.dismiss();
            } else {
                popupWindowShow();
            }
        } else if (vid == ResUtil.getId(mContext, "guild_customserver")) { // 进入联系客服
            FancyManager.getInstance().serviceSDK.startChatPage(this.getContext());
        } else if (vid == ResUtil.getId(mContext, "tv_register")) {
            if(!verifyCheckBox()){
                return;
            }
            activityMgr.pushViewToStack(new QuickRegisterView(ownerActivity, activityMgr));
        } else if (vid == ResUtil.getId(mContext, "guide_passseen")) {
            if (guide_passseen.isSelected()) {
                guide_passseen.setSelected(false);
                // eyeImg.setText("显示");
                guide_passseen.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_off"));
                passwordEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                guide_passseen.setSelected(true);
                // eyeImg.setText("隐藏");
                guide_passseen.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_on"));
                passwordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        }
    }
    
    private void onekeyregister() {
        final Map<String, String> regMap = GuildBaseInfo.getInstance()
            .oneKeyRegisterParamsGuild(mContext, "quick_reg");
        Log.e("mainview", "mainview" + regMap.toString());
        onekeySyncTask = new SdkAsyncTask<String>() {
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(regMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                if ((rst == null) || (rst.equals(""))) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    Log.e("startquickregrst", "startquickregrst:" + rst);
                    
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String msg = json.getString("data");
                    
                    if ((msg == null) || msg.equals("")) {
                        return;
                    }
                    JSONObject msgjson = new JSONObject(msg);
                    // 请求注册面板类型
                    String user_id = msgjson.optString("id");
                    String token = msgjson.optString("ticket");
                    String time = String.valueOf(msgjson.getInt("expires_in"));
                    String uname = msgjson.optString("name");
                    String upass = msgjson.optString("password");
    
                    if (msgjson.optString("game_discount") != null) {
                        String discount = msgjson.getString("game_discount");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, discount);
                    }else {
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, "0");
                    }
                    
                    //writeSDCard(msgjson.optString("uniqueId"));
                    // 判断是否有sourcePassword仅仅第一次会有
                    // 这里可优化，可以调整为，通过判断sOnekeyPass来调整，不重置sOnekeyPw为空值
                    // 所有接口都提前加密，就不需在put参数里判断
                    GuildBaseInfo.getInstance().setYuanUP(uname, upass);
                    
                    DBHelper.SDK_ACCOUNT s_acct = new DBHelper.SDK_ACCOUNT();
                    s_acct.auto_login = 1;
                    s_acct.user_name = uname;
                    s_acct.user_password = upass;
                    s_acct.is_valid = AccountHelper.ACCOUNT_VALID;
                    s_acct.user_id = user_id;
                    
                    Local_Account local_acct = new Local_Account();
                    local_acct.username = uname;
                    local_acct.password = upass;
                    local_acct.isValid = AccountHelper.ACCOUNT_VALID;
                    AccountHelper.updateLocalAccounts(local_acct);
                    GuildBaseInfo.setAcctsInfo(uname, user_id, upass);
                    
                    GlobalConfig.ticket = token;
                    GlobalConfig.stime = time;
                    GlobalConfig.sUid = user_id;
                    
                    if (dbHelper.isAccountPresent(s_acct)) {
                        dbHelper.updateAccount(s_acct);
                    } else {
                        dbHelper.insertNewAccount(s_acct);
                    }
                    AccountHelper.updateLocalAccounts(new Local_Account(
                        uname, upass, AccountHelper.ACCOUNT_VALID,
                        System.currentTimeMillis()));
                    
                    //0不实名 1提示 2强制
                    GlobalConfig.sRegCard = Integer.parseInt(msgjson.optString("pop_reg_idcard"));
                    String bindState = msgjson.optString("pop_reg_phone");
                    GlobalConfig.sBind = Integer.parseInt(bindState);
                    
                    int float_window=msgjson.has("float_window")?msgjson.optInt("float_window"):0;
                    SpMmkvUtils.putValue(mContext, SpMmkvUtils.KEY_FLOAT_DISPLAY, String.valueOf(float_window));
    
                    if (TextUtils.isEmpty(msgjson.optString("float_window_url"))) {
                        String httpsFloatUrl = msgjson.getString("float_window_url");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_HTTPS_FLOAT_URL, httpsFloatUrl);
                    }
                    
                    activityMgr.pushViewToStack(new TryPlayView(ownerActivity, activityMgr, uname, upass, token, time, user_id));
    
                    if (FancyManager.getInstance().isAdvertIdBool()) {
                        GameReportHelper.onEventRegister("onekey", true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
        };
        onekeySyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    private void popupWindowInit() {
        int width = this.findViewById(ResUtil.getId(mContext, "guild_popwindow")).getWidth();
        acctArray.clear();
        
        db_valid_accts = dbHelper.getAllValidAccounts();
        local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext, true);
        if (db_valid_accts.size() > 0) {
            for (int index = 0; index < db_valid_accts.size(); index++) {
                DBHelper.SDK_ACCOUNT obj = db_valid_accts.get(index);
                Logger.d("LoginView", "db_valid_accts index:" + index + "," + obj);
                acctArray.add(new Account(obj.user_name, obj.user_password, 1));
            }
        } else {
            Logger.d("LoginView", "db_valid_accts empty");
        }
    
        Logger.d("LoginView", "local_valid_accts:" + local_valid_accts.toString());
        if (local_valid_accts.size() > 0) {
            for (int index = 0; index < local_valid_accts.size(); index++) {
                Local_Account obj = local_valid_accts.get(index);
                
                int db_index = 0;
                for (; db_index < db_valid_accts.size(); db_index++) {
                    DBHelper.SDK_ACCOUNT db_obj = db_valid_accts.get(db_index);
                    if (db_obj.user_name.equals(obj.username)) {
                        break;
                    }
                }
                if (db_index == db_valid_accts.size()) {
                    acctArray.add(new Account(obj.username, obj.password, 1));
                }
            }
        }
    
        ArrayList<LoginView.Account> arrayList = new ArrayList<>();
        for (int i = 0; i < acctArray.size(); i++) {
            if(!TextUtils.isEmpty(acctArray.get(i).user_name)){
                arrayList.add(acctArray.get(i));
            }
        }
        acctArray = arrayList;
        
        if (adapter == null) {
            adapter = new AccountShowAdatper();
        }
        adapter.setAdapterObj(acctArray);
        
        if (popListView == null) {
            popListView = new ListView(mContext);
        }
        
        popListView.setDivider(getResources().getDrawable(
            ResUtil.getDrawableId(mContext, "guild_img_line")));
        popListView.setCacheColorHint(0xff909090);
        popListView.setOnItemClickListener(this);
        popListView.setAdapter(adapter);
        
        if (popupWindow == null) {
            popupWindow = new PopupWindow(popListView, width,
                LayoutParams.WRAP_CONTENT, true);
        }
        
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
            ResUtil.getDrawableId(mContext, "guild_input_down")));
        
        popupWindow.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                if (acctDownIV != null) {
                    guild_login_down_img.setBackgroundResource(ResUtil
                        .getDrawableId(mContext, "guild_arrow_down"));
                }
            }
        });
    }
    
    public void popupWindowShow() {
        View view = this.findViewById(ResUtil.getId(mContext, "guild_popwindow"));
        if (acctDownIV != null) {
            guild_login_down_img.setBackgroundResource(ResUtil.getDrawableId(
                mContext, "guild_arrow_down"));
        }
        popupWindow.showAsDropDown(view, 0, 30);
    }
    
    public class AccountShowAdatper extends BaseAdapter {
        
        ArrayList<LoginView.Account> array;
        
        public void setAdapterObj(ArrayList<LoginView.Account> array) {
            this.array = array;
            notifyDataSetChanged();
        }
        
        @Override
        public int getCount() {
            return array.size();
        }
        
        @Override
        public Object getItem(int position) {
            return array.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            final String curUser = array.get(position).user_name;
            final String curPasswd = array.get(position).user_password;
            
            if (convertView == null) {
                convertView = inflater.inflate(ResUtil.getLayoutId(mContext,
                    "guild_account_list_item"), null);
                holder = new ViewHolder();
                holder.account = (TextView) convertView.findViewById(ResUtil
                    .getId(mContext, "guild_account_name"));
                holder.delete = (RelativeLayout) convertView
                    .findViewById(ResUtil.getId(mContext,
                        "guild_account_dele"));
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Logger.d("LoginView", "AccountShowAdatper user:" + array.get(position).user_name+", valid:"+array.get(position).is_valid);
            
            holder.account.setText(curUser);
            String userandpassPP = curUser + "," + curPasswd + "," + position + "";
            holder.delete.setTag(userandpassPP);
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (arg0 != null) {
                        String userpass = arg0.getTag().toString();
                        String username = "";
                        String passowrd = "";
                        String pointsave = "0";
                        String[] sourceStrArray = userpass.split(",");
                        for (int i = 0; i < sourceStrArray.length; i++) {
                            if (i == 0) {
                                username = sourceStrArray[i];
                            } else if (i == 1) {
                                passowrd = sourceStrArray[i];
                            } else if (i == 2) {
                                pointsave = sourceStrArray[i];
                            }
                        }
                        staticdeleteusername = username;
                        savepoint = pointsave;
                        staticusername = username;
                        staticpassword = passowrd;
                    }
                    
                    deleteDialog = new DeleteUserDialog(ownerActivity, 0, new DeleteCallback() {
                        @Override
                        public void onDelete() {
                            handleDeleteUser();
                        }
                    });
                    deleteDialog.show();
                    
                    if (position == 1) {
                        currentpostion = 1;
                    } else {
                        currentpostion = 0;
                    }
                }
            });
            return convertView;
        }
    }
    
    private void handleDeleteUser() {
        Local_Account accs = new Local_Account(staticusername, staticpassword, 0);
        acctArray.remove(savepoint);
    
        Logger.d("LoginView", "handleDeleteUser size:" + acctArray.get(0).user_name + ", staticusername:" + staticusername);
        if (!acctArray.isEmpty()) {
            // 只有一个时删除会清空
            if (acctArray.size() == 1) {
                usernameEt.setText("");
                passwordEt.setText("");
            
                dbHelper.deleteAccountByUsername(staticusername);
                AccountHelper.updateLocalAccounts(accs);
                popupWindow.dismiss();
                adapter.notifyDataSetChanged();
                CommMessage.currentUserName = "";
                CommMessage.currentPassword = "";
                return;
            }
            // 删除后默认显示列表第2个帐号，若删第2个帐号则显示第1个
            LoginView.Account acc = acctArray.get(1);
            if (currentpostion == 1) {
                acc = acctArray.get(0);
            }
        
            String username = acc.user_name;
            String password = acc.user_password;
            usernameEt.setText(username);
            passwordEt.setText(password);
        } else {
            usernameEt.setText("");
            passwordEt.setText("");
        }
    
        dbHelper.setAccountInvalid(staticusername);
        AccountHelper.updateLocalAccounts(accs);
        popupWindow.dismiss();
        adapter.notifyDataSetChanged();
    
        CommMessage.currentUserName = usernameEt.getText().toString();
        CommMessage.currentPassword = passwordEt.getText().toString();
    }
    
    private static class ViewHolder {
        TextView account;
        RelativeLayout delete;
    }
    
    static class Account {
        
        String user_name;
        String user_password;
        int is_valid;
        
        Account(String user, String passwd, int isValid) {
            this.user_name = user;
            this.user_password = passwd;
            this.is_valid = isValid;
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
        Account account = acctArray.get(position);
        String username = account.user_name;
        String passwd = account.user_password;
        
        usernameEt.setText(username);
        passwordEt.setText(passwd);
        
        CommMessage.currentUserName = username;
        CommMessage.currentPassword = passwd;
        CommMessage.currentRealmainUserName = username;
        CommMessage.currentRealmainPassword = passwd;
        chooseCurrentUser = true;
        popupWindow.dismiss();
    }
    
    public static void editclear() {
        usernameEt.setText("");
        passwordEt.setText("");
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.e("loginview-keyback", "loginview-keyback");
            activityMgr.finishDialogOrActivity();
            return false;
        } else {
            Log.e("loginview_keyback", "loginview_keyback");
            return super.onKeyDown(keyCode, event);
        }
    }
    
    private void judgeIfResetPassword() {
        if (CommMessage.sFindPass != null) {
            Log.e("loginviewreset", "loginviewreset");
            new Thread() {
                public void run() {
                    ownerActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 显示在ui
                            usernameEt.setText(CommMessage.sFindUser);
                            passwordEt.setText(CommMessage.sFindPass);
                            // 写入数据库
                            Local_Account local_acct = new Local_Account();
                            local_acct.username = CommMessage.sFindUser;
                            local_acct.password = CommMessage.sFindPass;
                            local_acct.isValid = AccountHelper.ACCOUNT_VALID;
                            AccountHelper.updateLocalAccounts(local_acct);
                            // 置空防止下次跳转
                            CommMessage.sFindPass = null;
                            CommMessage.sFindUser = null;
                        }
                    });
                }
                
                ;
            }.start();
        }
    }
    
}
